package com.ysd.util;

import java.io.IOException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {
	private static String CONFIG_FILE = "mybatisConfig.xml";
	private static SqlSessionFactory sessionFactory;
	private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
	/**
	 * * 闂傚牊鐟﹂敓鎴掔閸ㄥ灚鎱ㄧ�ｎ亜顕ч柛褎顨愮槐婵堬拷鐟版湰閸ㄦ岸宕氬☉妯肩处闁哥儐鍨粩鎾儍閿燂拷 SqlSessionFactory 閻庣數顢婇挅锟�
	 */
	static {
		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
		try {
			sessionFactory = builder.build(Resources.getResourceAsStream(CONFIG_FILE));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * * 缂佹崘娉曢埢鑲╋拷鐟邦槸閸欏繘宕烽弶鍨仭鐎点倧鎷� SqlSession 閻庣數顢婇挅锟�
	 * *@return SqlSession 閻庣數顢婇挅锟�
	 */
	public static SqlSession getSqlSession() {
		SqlSession session = threadLocal.get();
		if (session == null) {
			session = sessionFactory.openSession();
			threadLocal.set(session);
		}
		return session;
	}

	public static void closeSqlSession() {
		SqlSession session = threadLocal.get();
		if (session != null) {
			session.close();
			threadLocal.set(null);
		}
	}

	/**
	 *  闁兼儳鍢茬欢锟� Dao 闁规亽鍎辫ぐ娑氾拷鍦仧楠炲洨鐚鹃敓锟�
	 *  
	 *  @param clazz Dao 闁规亽鍎辫ぐ娑氱尵鐠囪尙锟斤拷 
	 *  @return Dao 闁规亽鍎辫ぐ娑氾拷鍦仧楠炲洨鐚鹃敓锟�
	 */
	public static <T> T getMapper(Class<T> clazz) {
		return getSqlSession().getMapper(clazz);
	}

}
